package com.myh.gulimall.product.service.impl;

import com.myh.gulimall.product.dao.CategoryBrandRelationDao;
import com.myh.gulimall.product.dao.CategoryDao;
import com.myh.gulimall.product.entity.CategoryBrandRelationEntity;
import com.myh.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myh.common.utils.PageUtils;
import com.myh.common.utils.Query;

import com.myh.gulimall.product.dao.BrandDao;
import com.myh.gulimall.product.entity.BrandEntity;
import com.myh.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params), queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateDetails(BrandEntity brand) {
        brandDao.updateById(brand);
        if (!StringUtils.isEmpty(brand.getName())) {
            //同步更新其他关联表当中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
            //TODO 更新其他关联
        }
    }

    @Override
    public String findBrandNameByBrandId(Long brandId) {

        BrandEntity brandEntity = brandDao.selectById(brandId);
        if (!Objects.isNull(brandEntity)){
            return brandEntity.getName();
        }else {
            return null;
        }
    }

}